package com.example.activity

import android.annotation.SuppressLint
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.appcompat.app.ActionBar
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.example.activity.fragment.tab.Tab1
import com.example.activity.fragment.tab.Tab2
import com.example.activity.fragment.tab.Tab3
import com.example.activity.fragment.tab.Tab4
import java.util.*
import kotlin.properties.Delegates

class TabBarActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tab_bar)

        supportActionBar?.navigationMode = ActionBar.NAVIGATION_MODE_TABS
        supportActionBar?.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE)

        //把各个标签页添加进actionBar中
        supportActionBar?.addTab(
            supportActionBar!!.newTab().setText("首页").setTabListener(TabListener<Tab1>(Tab1::class.java))
        )
        supportActionBar?.addTab(
            supportActionBar!!.newTab().setText("第二页").setTabListener(TabListener<Tab2>(Tab2::class.java))
        )
        supportActionBar?.addTab(
            supportActionBar!!.newTab().setText("第三页").setTabListener(TabListener<Tab3>(Tab3::class.java))
        )
        supportActionBar?.addTab(
            supportActionBar!!.newTab().setText("第四页").setTabListener(TabListener<Tab4>(Tab4::class.java))
        )

    }

    /**
     * 定义一个监听器泛型类
     */
    inner class TabListener<T : Fragment>(private val clazz: Class<T>) : ActionBar.TabListener {
        private var fragment: Fragment? = null

        override fun onTabReselected(tab: ActionBar.Tab?, ft: FragmentTransaction?) {
        }

        @RequiresApi(Build.VERSION_CODES.N)
        override fun onTabUnselected(tab: ActionBar.Tab?, ft: FragmentTransaction?) {
            if (Objects.nonNull(fragment)){
                fragment?.let { ft?.detach(it) }
            }
        }

        @RequiresApi(Build.VERSION_CODES.N)
        override fun onTabSelected(tab: ActionBar.Tab?, ft: FragmentTransaction?) {
            if (Objects.isNull(fragment)){
                fragment = Fragment.instantiate(this@TabBarActivity,clazz.name)
                ft?.add(android.R.id.content, fragment!!,null)
            }
            fragment?.let { ft?.attach(it) }
        }

    }

}

